<?php
/***********************************************
	This class would print the JSON data in a
	human readable format.
************************************************/
class JSONPrettyPrinter {
	private $prettyPrintedResults = NULL;
	private $char = NULL;
	private $post = NULL;
	private $level = NULL;
	private $inQuotes = NULL;
	private $prevChar = NULL;
	private $jsonLength = NULL;
	private $endLineLevel = NULL;
	private $newLineLevel = NULL;
	
	/************************************************************/
	
	function __construct() {
		$this->prettyPrintedResults = '';
		$this->level = 0;
		$this->post = '';
		$this->prevChar = '';
		$this->inQuotes = FALSE;
	}
	
	/************************************************************/
	
	function prettyPrint($encodedJSONData) {
		$this->jsonLength = strlen($encodedJSONData);

	    for ($i = 0; $i < $this->jsonLength; $i++) {
			$this->post = "";
			$this->newLineLevel = NULL;
			$this->char = $encodedJSONData[$i];
        
			if ($this->endLineLevel !== NULL) {
            	$this->newLineLevel = $this->endLineLevel;
            	$this->endLineLevel = NULL;
        	}
        
			if ($this->char === '"' && $this->prevChar != '\\') {
            	$this->inQuotes = !$this->inQuotes;
        	} elseif (!$this->inQuotes) {
            	switch ($this->char) {
                	case '}': case ']':
                    	$this->level--;
                    	$this->endLineLevel = NULL;
                    	$this->newLineLevel = $this->level;
                    break;
					/************************************************************/
                	case '{': case '[':
                    	$this->level++;
					case ',':
                    	$this->endLineLevel = $this->level;
                    break;
					/************************************************************/
                	case ':':
                    	$this->post = " ";
                    break;
					/************************************************************/
                	case " ": case "\t": case "\n": case "\r":
                    	$this->char = "";
                    	$this->endLineLevel = $this->newLineLevel;
                    	$this->newLineLevel = NULL;
                    break;
            	} // [End] --> switch
        	}
        
			if ($this->newLineLevel !== NULL) {
            	$this->prettyPrintedResults .= "\n".str_repeat("\t", $this->newLineLevel);
        	}
        
			$this->prettyPrintedResults .= $this->char.$this->post;
        	$this->prevChar = $this->char;
    	}

    	return $this->prettyPrintedResults;
	}
}
?>